package StatePattern.first;

public class GumballMachine {

    final static int SOLD_OUT = 0;
    final static int NO_QUARTER = 1;
    final static int HAS_QUARTER = 2;
    final static int SOLD = 3;

    int state = SOLD_OUT;
    int count = 0;

    public GumballMachine(int count){
        this.count = count;
        if(count>0){
            state = NO_QUARTER;
        }
    }

    /**
     * 投入硬币
     */
    public void insertQuarter(){
        switch(state){
            case HAS_QUARTER:
                System.out.println("你已经投了一枚硬币，不能再投了哦！！");
                break;
            case NO_QUARTER:
                state = HAS_QUARTER;
                System.out.println("你投了一枚硬币，请做出拉杆操作！");
                break;
            case SOLD_OUT:
                System.out.println("不要意思，糖果已经卖完了，你不能投了哦");
                break;
            case SOLD:
                System.out.println("请等一下，我们正在准备给您一个糖果");
        }
    }

    /**
     * 退回硬币
     */
    public void ejectQuarter(){
        switch(state){
            case HAS_QUARTER:
                System.out.println("退回您的硬币");
                state = NO_QUARTER;
                break;
            case NO_QUARTER:
                System.out.println("你还没有投硬币，不能进行退回操作");
                break;
            case SOLD_OUT:
                System.out.println("不要意思，不还没有投硬币呢！");
                break;
            case SOLD:
                System.out.println("抱歉，你已经拉动拉杆了哦，不能退回了哦");
        }
    }

    public void turnCrank(){
        switch(state){
            case HAS_QUARTER:
                System.out.println("恭喜您成功拉杆了");
                state = SOLD;
                dispense();
                break;
            case NO_QUARTER:
                System.out.println("你还没有投硬币，不能进行拉杆操作");
                break;
            case SOLD_OUT:
                System.out.println("不要意思，糖果已经卖完了");
                break;
            case SOLD:
                System.out.println("抱歉，你已经拉动拉杆了哦，不能再拉了哦，你需要投入硬币才能再拉哦");
        }
    }

    /**
     * 发放糖果操作
     */
    public void dispense(){
        switch(state){
            case HAS_QUARTER:
                System.out.println("异常：不该进入此状态");
                break;
            case NO_QUARTER:
                System.out.println("你需要先投入硬币哦");
                break;
            case SOLD_OUT:
                System.out.println("异常：不要意思，糖果已经卖完了");
                break;
            case SOLD:
                System.out.println("为您发放一个糖果哦： 🍬 ");
                count-=1;
                if(count==0){
                    System.out.println("最后一颗糖果已经买完了");
                    state = SOLD_OUT;
                }else{
                    state = NO_QUARTER;
                }
                break;
        }
    }

    @Override
    public String toString() {
        return "GumballMachine{" +
                "state=" + state +
                ", count=" + count +
                '}';
    }
}
